/*
 *  $Id: Time.cs 898 2009-11-28 16:12:26Z thenn.erannor $
 *	This file is a part of Ragima CCG.
 *	(C) 2008 Ragima development group.
 *
 *	Licensed under the terms of the GNU GPL License version 2.
 *
 */

using System;

namespace Ragima {
    [Flags]
    public enum TimePhase: int {
        OwnOffence = 1,
        OwnDefence = 2,
        Own = OwnOffence | OwnDefence,
        EnemyOffence = 4,
        EnemyDefence = 8,
        Enemy = EnemyOffence | EnemyDefence,
        All = Own | Enemy
    }

    /// <summary>
    /// Эффект: действие на X фаз (ходов/4) (число)
    /// Групповой эффект, определяющий действие в течение некоторое числа фаз (ходов/4).
    /// </summary>
    public class TimeAffect: GroupAffect {
        private TimePhase _events;
        private int _phases;

        public TimeAffect(int phases): this(phases, TimePhase.All) {}
        public TimeAffect(int phases, Affect sub): this(phases, TimePhase.All, sub) {}
        public TimeAffect(int phases, TimePhase events): base() {
            _events = events;
            _phases = phases;
        }
        public TimeAffect(int phases, TimePhase events, Affect sub): this(phases, events) {
            Add(sub);
        }

        public override string Id {
            get { return "time"; }
        }

        public override bool IsEnded {
            get { return _phases <= 0; }
        }

        public int Phases { get { return _phases; } }

        public override Affect Clone() {
            TimeAffect copy = new TimeAffect(_phases, _events);
            copy.AddCloned(this);
            return copy;
        }

        public override void SetAffect() {
            base.SetAffect();
            if ((_events & TimePhase.OwnOffence) != 0) GlobalSummary.OnStartOffencePhase += DoPhase;
            if ((_events & TimePhase.OwnDefence) != 0) GlobalSummary.OnStartDefencePhase += DoPhase;
            if ((_events & TimePhase.EnemyOffence) != 0) EnemySummary.OnStartOffencePhase += DoPhase;
            if ((_events & TimePhase.EnemyDefence) != 0) EnemySummary.OnStartDefencePhase += DoPhase;
        }
        public override void ResetAffect() {
            base.ResetAffect();
            if ((_events & TimePhase.OwnOffence) != 0) GlobalSummary.OnStartOffencePhase -= DoPhase;
            if ((_events & TimePhase.OwnDefence) != 0) GlobalSummary.OnStartDefencePhase -= DoPhase;
            if ((_events & TimePhase.EnemyOffence) != 0) EnemySummary.OnStartOffencePhase -= DoPhase;
            if ((_events & TimePhase.EnemyDefence) != 0) EnemySummary.OnStartDefencePhase -= DoPhase;
        }

        private void DoPhase() {
            DecrementPhases();
        }
        protected virtual void DecrementPhases() {
            _phases--;
            if (IsEnded) Owner.RemoveEndedAffects();
        }
    }
}